#include <semaphore.h>
class ZeroEvenOdd {
private:
    int n;
    sem_t f0, f1, f2;

public:
    ZeroEvenOdd(int n) {
        this->n = n;
        sem_init(&f0, 0, 1);
        sem_init(&f1, 0, 0);
        sem_init(&f2, 0, 0);
    }

    // printNumber(x) outputs "x", where x is an integer.
    void zero(function<void(int)> printNumber) {

        for (int i = 1; i <= n; i++) {
            sem_wait(&f0);
            printNumber(0);
            if (i % 2) {
                sem_post(&f1);
            } else {
                sem_post(&f2);
            }
        }
    }

    void even(function<void(int)> printNumber) {

        for (int i = 2; i <= n; i += 2) {
            sem_wait(&f2);
            printNumber(i);
            sem_post(&f0);
        }
    }

    void odd(function<void(int)> printNumber) {

        for (int i = 1; i <= n; i += 2) {
            sem_wait(&f1);
            printNumber(i);
            sem_post(&f0);
        }
    }
};
